# Importing Data
GERMANY <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Iran/Germany.xlsx")

# Checking the Imported Data
View(GERMANY)

# Creating Time Series Data
GERMANY_ts <- ts(GERMANY, start=c(2004,1), end=c(2018,07), frequency=12)

# Viewing and Checking the Created Time Series Data
GERMANY_ts
sum(is.na(GERMANY_ts))
library(forecast)
GERMANY_ts <- tsclean(GERMANY_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(GERMANY_ts)
plot(aggregate(GERMANY_ts,FUN=mean))

# Decomposing
GERMANY_ts_decomp <- decompose(GERMANY_ts)
plot(GERMANY_ts_decomp)

# Testing for Stationarity
acf(GERMANY_ts, lag.max=20)
pacf(GERMANY_ts, lag.max=20)

# To see any seasonal effect
boxplot(GERMANY_ts~cycle(GERMANY_ts))

# To remove trend effect
GERMANY_ts_diff <- diff(GERMANY_ts)
plot(GERMANY_ts_diff)

# To remove variance effect
GERMANY_ts_log <- log(GERMANY_ts)
plot(GERMANY_ts_log)

# To remove both (Trend and Variance) effects
GERMANY_ts_both <- diff(log(GERMANY_ts))
plot(GERMANY_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(GERMANY_ts, lag.max=20)
acf(log(GERMANY_ts), lag.max=20)
acf(diff(GERMANY_ts), lag.max=20)
acf(diff(log(GERMANY_ts)), lag.max=20)
pacf(GERMANY_ts, lag.max=20)
pacf(log(GERMANY_ts), lag.max=20)
pacf(diff(GERMANY_ts), lag.max=20)
pacf(diff(log(GERMANY_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
GERMANY_ts_model <- auto.arima(GERMANY_ts)
GERMANY_ts_model
GERMANY_ts_model <- auto.arima(GERMANY_ts, ic="aic", trace = TRUE)
GERMANY_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(GERMANY_ts_model$resid)
acf(GERMANY_ts_model$residuals, main='ACF Residual')
pacf(GERMANY_ts_model$residuals, main='ACF Residual')
Box.test(GERMANY_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
GERMANY_ts_forecast <- forecast (GERMANY_ts_model, level=c(95), h=269)
plot(GERMANY_ts_forecast)
GERMANY_ts_forecast             


write.table(GERMANY_ts_forecast, file="Germany_TSA.csv", sep=",")
